<template>
  <div id="app">
    <toolbar-component 
        :sidebar-visible="sidebarVisible"
        @toggle-sidebar="toggleSidebar"
        @new-file="createNewFile"
        @open-settings="showSettings = true">
      </toolbar-component>
    
    <div class="main-container">
      <div class="left-panel" :class="{ hidden: !sidebarVisible }">
        <sidebar-component 
          ref="sidebar"
          :visible="sidebarVisible"
          @file-selected="loadFile"
          @file-deleted="handleFileDeleted">
        </sidebar-component>
      </div>
      
      <div class="right-panel">
        <editor-component 
          :content="currentContent"
          :rendered-html="renderedHTML"
          @content-changed="updateContent">
        </editor-component>
      </div>
    </div>
    
    <modal-manager
        v-model:visible="modalState.visible"
        :title="modalState.title"
        :message="modalState.message"
        :type="modalState.type"
        :confirm-text="modalState.confirmText"
        :cancel-text="modalState.cancelText"
        :show-close="modalState.showClose"
        :show-cancel="modalState.showCancel"
        :show-confirm="modalState.showConfirm"
        :close-on-overlay="modalState.closeOnOverlay"
        @confirm="modalState.onConfirm?.()"
        @cancel="modalState.onCancel?.()"
        @close="modalState.onClose?.()">
      </modal-manager>

      <settings-component 
        v-if="showSettings" 
        @close="showSettings = false">
      </settings-component>
    </div>
</template>

<script setup>
import { ref, watch, nextTick, onMounted } from 'vue'
import ToolbarComponent from './components/ToolbarComponent.vue'
import SidebarComponent from './components/SidebarComponent.vue'
import EditorComponent from './components/EditorComponent.vue'
import ModalManager from './components/ModalManager.vue'
import SettingsComponent from './components/SettingsComponent.vue'
import { useModal } from './composables/useModal.js'

// 响应式数据
const sidebarVisible = ref(true)
const currentContent = ref('# 欢迎使用Markdown编辑器\n\n开始编写您的Markdown文档...')
const renderedHTML = ref('<h1>1111111xxx</h1>')
const currentFile = ref(null)
const autoSaveTimer = ref(null)
const isSaving = ref(false)
const sidebarRef = ref(null)
const showSettings = ref(false)

// 使用模态框
const { modalState } = useModal()

// 方法定义
const toggleSidebar = () => {
  sidebarVisible.value = !sidebarVisible.value
}

const loadFile = async (file) => {
  try {
    currentFile.value = file
    const result = await window.electronAPI.readFile(file.path)
    if (result.success) {
      currentContent.value = result.content
    } else {
      throw new Error(result.error)
    }
    
    // 设置光标到文件末尾
    nextTick(() => {
      const textarea = document.querySelector('.markdown-editor')
      if (textarea) {
        textarea.focus()
        textarea.setSelectionRange(textarea.value.length, textarea.value.length)
      }
    })
  } catch (error) {
    console.error('加载文件失败:', error)
    alert('加载文件失败: ' + error.message)
  }
}

const updateContent = (newContent) => {
  currentContent.value = newContent
  scheduleAutoSave()
}

const renderMarkdown = (content) => {
  try {
    console.log('开始渲染markdown，内容长度:', content.length)
    const html = window.electronAPI.marked.parse(content)
    console.log('渲染完成，HTML长度:', html.length)
    renderedHTML.value = html
    nextTick(() => {
      console.log('nextTick after renderedHTML update')
      renderedHTML.value = html
    })
    console.log(renderedHTML.value)
  } catch (error) {
    console.error('渲染失败:', error)
    renderedHTML.value = '<p>渲染错误: ' + error.message + '</p>'
  }
}

const scheduleAutoSave = () => {
  // 清除之前的定时器
  if (autoSaveTimer.value) {
    clearTimeout(autoSaveTimer.value)
  }
  
  // 设置新的自动保存定时器（2秒后执行）
  autoSaveTimer.value = setTimeout(() => {
    autoSave()
  }, 2000)
}

const autoSave = async () => {
  if (!currentFile.value || isSaving.value) return
  
  isSaving.value = true
  try {
    const result = await window.electronAPI.saveFile(currentFile.value.path, currentContent.value)
    if (result.success) {
      console.log('文件已自动保存')
      
      // 更新侧边栏显示名称
      await updateSidebarFileName()
    } else {
      console.error('自动保存失败:', result.error)
    }
  } catch (error) {
    console.error('自动保存出错:', error)
  } finally {
    isSaving.value = false
  }
}

const updateSidebarFileName = async () => {
  if (!currentFile.value) return
  
  try {
    // 获取文件的第一行作为新名称
    const result = await window.electronAPI.readFileFirstLine(currentFile.value.path)
    const newName = result.firstLine || '未命名文档'
    
    // 更新当前文件对象
    currentFile.value.name = newName
    
    // 更新侧边栏中的文件列表
    if (sidebarRef.value) {
      const fileIndex = sidebarRef.value.files.findIndex(f => f.path === currentFile.value.path)
      if (fileIndex !== -1) {
        sidebarRef.value.files[fileIndex].name = newName
      }
    }
  } catch (error) {
    console.error('更新文件名失败:', error)
  }
}

const createNewFile = () => {
  if (sidebarRef.value) {
    sidebarRef.value.createNewFile()
  }
}

const handleFileDeleted = (deletedFile) => {
  // 如果删除的是当前打开的文件，清空编辑器
  if (currentFile.value && currentFile.value.path === deletedFile.path) {
    currentFile.value = null
    currentContent.value = '# 欢迎使用Markdown编辑器\n\n开始编写您的Markdown文档...'
    renderedHTML.value = '<h1>欢迎使用Markdown编辑器</h1><p>开始编写您的Markdown文档...</p>'
  }
}

// 监听内容变化
watch(currentContent, (newContent) => {
  renderMarkdown(newContent)
})

// 生命周期
onMounted(() => {
  // 初始化时渲染一次
  renderMarkdown(currentContent.value)
})
</script>
